import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
  Button,
  Icon,
  Spin,
  Layout,
  Select,
  Popover,
  Modal,
  Form,
  message,
  Tabs,
  Checkbox,
  InputNumber,
  Input
} from 'antd';
import 'styles/data-center/report-management/custom-report/edit-custom-report.scss';
import DataDragItem
  from 'containers/data-center/report-management/custom-report/drag-source/data-drag-item';
import DataDropTarget
  from 'containers/data-center/report-management/custom-report/drop-target/data-drop-target';
import DataFakeDropLayout
  from 'containers/data-center/report-management/custom-report/drop-target/data-fake-drop-layout';
import CustomReportService
  from 'containers/data-center/report-management/custom-report/custom-report.service';
import InputLanguage from 'components/template/input-language';
import Graphic from 'containers/data-center/report-management/custom-report/graphic';
import IndexAdvanceSearch
  from 'containers/data-center/report-management/custom-report/graphic/index-advance-search';
import { deepCopy, messages, removeArrayItemByKey, sortByProperty, scrollToMyDestination } from 'share/common';
import {
  iconMap,
  graphList,
  GraphicMap,
  boxMap,
  fontSizeOptions
} from 'containers/data-center/report-management/custom-report/custom-report.modal';
import DefaultValue
  from 'containers/data-center/report-management/custom-report/graphic/default-value/default-value';
import UniversalReportService
  from 'containers/data-center/report-management/custom-report/graphic/default-value/custom-report.service';

import { handleDefaultValue } from 'containers/data-center/report-management/custom-report/graphic/default-value/default-value.service';

import { connect } from 'react-redux';
import debounce from 'lodash.debounce';

const { Content, Sider } = Layout;
const TabPane = Tabs.TabPane;
const Option = Select.Option;
const confirm = Modal.confirm;
const Search = Input.Search;
import { clearPending } from 'share/httpFetch';
import DroppedDataDragItem from './drag-source/dropped-data-drag-item';

function mapStateToProps(state) {
  return {
    language: state.main.language,
    company: state.login.company,
    tenant: state.login.tenant
  };
}

@Form.create()
@connect(mapStateToProps)

class EditCustomReport extends Component {
  constructor(props) {
    super(props);
    this.state = {
      dataModalList: [],
      DataModalAttributes: [],
      loading: false,
      loadingAll: true,
      noUpdate: false, // graphic table 更新不更新
      linkableLoading: false, //可联动图形表 loading
      linkableList: [], //可联动图形表Id list
      btnLoading: false,
      selectDimensionDataList: [], //通用维度   或   维度（列）
      selectDimensionRowDataList: [], //  维度（行）
      selectIndicatorDataList: [],// 指标
      selectShowDataList: [],// 展示字段
      selectCriteriaDataList: [],// 筛选器
      editData: {},
      ModalListNameArray: [], //所有涉及到的数据模型数组
      fakeDataLength: 0,  //假数据长度
      fakeData: [], //假数据数组
      SearchKeyWord: '', //搜索 数据模型 属性 keyword
      hoverItem: {}, //鼠标 hover 的 单个属性
      focusBox: undefined, //聚焦的box
      currentReportPrivate: {}, // 各报表私有配置的载体 (不知道这是干嘛的)
      CurrentSourceReportId: undefined, //当前数据模型id
    };
    this.handleOnDragDroppedItem = debounce(this.handleOnDragDroppedItem, 0);
    this.handleSearchModalAttributes = debounce(this.handleSearchModalAttributes, 300);
    this.handleItemMouseOver = debounce(this.handleItemMouseOver, 300);
    window.editCustomReportCancelConfirm = () => {
      this.onPageCanceled();
    };
    // this.singleTemplate = {
    //   reportId: this.props.customReportData.id,
    //   sourceReportId: null, //数据模型id
    //   name: null, //图表name
    //   chartType: null, //图表类型
    //   limitNum: null, //   显示前几条数据
    //   showScreen: null, //半屏/全屏
    //   operateType: null, //
    //   fixedColumnsNum: null,  // 表格固定前几列
    //   showLabelFlag: null,  // 显示数据标签
    //   showDimensionFlag: null,  //显示维度值
    //   showIndicatorFlag: null,  //显示指标值
    //   showPercentFlag: null,  //显示百分比
    //   showLegendLocation: null, // 显示图例位置
    //   style: null,  // 单指标图 指标数字大小
    //   reportChartDetails: [
    //     {
    //       sourceReportId: null, //数据模型id
    //       reportColumnId: null, //数据模型里的单个属性id
    //       fieldType: null,  // 维度/指标 dimension/indicator
    //       fieldDisplayName: null, //维度/指标 名
    //       i18n: null
    //     }
    //   ],
    //   i18n: null
    // };
  }

  componentWillMount() {
  }

  /** 欢迎来到第二层 编辑 图表 筛选器 详情：
   *
   本页面功能：
   1. 选择该图表数据模型（图形表，明细表）      展示所有 图形表设计的数据模型（筛选器）
   2. 定义图表名
   3. 定义    1.图表的 维度/指标    2.筛选器的 筛选字段     3.明细表的  展示字段
   4. 定义图表类型，在这儿 用户可以 继续切换图表类型
   5. 设置图表/筛选器/明细表的详情（
      1. 指标图： 字体大小
      2. 横向/纵向 柱状图： 显示前n条数据，显示数据标签
      3. 面积图/雷达图/折线图：显示前n条数据，显示数据标签，显示图例
      4. 饼图：显示前n条数据，显示维度值，显示指标值，显示百分比，显示图例
      5. 明细表：固定前N列数据，允许导出操作
      6. 筛选器：默认值设置
   ）
   6. 图形表联动 设置 （联动 同 数据模型 图表） 横向纵向柱状图、饼图、折线图、面积图  可设置
   7. 图表预览 这里是 前端随机生成的假数据 生成规则： 随机生成3-11条假数据，数字数据范围 0 ~ 1000， 字符串数据 计数范围 0 ~ 10
   */

  // 组件需要 获取到 当前图表的详情信息，如果有对应数据模型 需要获取数据模型信息，以及查询 是否可以联动其他 同模型图表
  // 每个接口都需要获取到数据后 才能 操作编辑 图表，因此这儿用了 Promise.all
  componentDidMount() {
    Promise.all([this.initData(), this.getDataModalList()])
      .finally(() => {
        this.setState({ loadingAll: false }, () => {
          this.getLinkableList();
        });
      });
  }

  //获取可联动 图表
  getLinkableList = (newSourceReportId) => {
    const { CurrentSourceReportId, editData } = this.state;
    const { customReportData } = this.props;
    let params = {
      sourceReportId: newSourceReportId || CurrentSourceReportId,
      reportId: customReportData.id,
      reportChartId: editData.id
    };
    return new Promise((resolve, reject) => {
      if ((newSourceReportId || CurrentSourceReportId) && editData.key !== 'criteria') {
        this.setState({ linkableLoading: true });
        CustomReportService.getLinkableSingleGraphicIds(params)
          .then((res) => {
            if (res.status === 200) {
              this.setState({ linkableLoading: false, linkableList: res.data });
            }
          })
          .catch((err) => {
            reject(err);
          });
        this.getTableData();
      } else {
        resolve();
      }
    });
  };

  componentWillUnmount() {
    clearPending();
    if (window.editCustomReportCancelConfirm) {
      delete window.editCustomReportCancelConfirm;
    }
  }

  getTableData = () => {
    if (['perspective', 'detail_list'].indexOf(this.state.editData.key) !== -1) {
      this.setState({noUpdate: false}, ()=>{
        this.GraphicRef.IndexTableRef.willReload();
      })
    }
  }

  // 拖拽单个数据模型属性 结束
  onDragEnd = () => {
    this.getTableData();
  }

  //生成假数据
  generateFakeData = (isFromClick) => {
    const { selectDimensionDataList, selectDimensionRowDataList, selectIndicatorDataList, selectShowDataList, editData } = this.state;
    let fakeDataList = [], times;
    if (editData.narrowRangeFlag)
      times = Math.floor(Math.random() * 50) + 30;
    else
      times = Math.floor(Math.random() * 8) + 5;
    for (let i = 0; i < times; i++) {
      if (i < times) {
        fakeDataList.push(generate());
      }
      if (i === times - 1) {
        this.setState({ fakeDataLength: fakeDataList.length, fakeData: fakeDataList }, ()=>{
          if (isFromClick)
            this.getTableData();
        });
      }
    }

    function generate() {
      let singleFakeData = {};
      selectDimensionDataList.forEach((item) => {
        singleFakeData[item.columnPropName] = `${item.fieldDisplayName || item.columnDisplayName}${Math.floor(Math.random() * 100)}`;
      });
      selectDimensionRowDataList.forEach((item) => {
        singleFakeData[item.columnPropName] = `${item.fieldDisplayName || item.columnDisplayName}${Math.floor(Math.random() * 100)}`;
      });
      selectIndicatorDataList.forEach((item, index) => {
        if (!(['bigdecimal', 'number'].indexOf(item.dataType) !== -1)) { //计数
          singleFakeData[item.columnPropName] = Math.floor(Math.random() * 50);
        } else { //纯数字
          singleFakeData[item.columnPropName] = Math.floor(Math.random() * 1000);
        }
      });
      selectShowDataList.forEach((item) => {
        if (!(['bigdecimal', 'number'].indexOf(item.dataType) !== -1)) { //计数
          singleFakeData[item.columnPropName] = `${item.fieldDisplayName || item.columnDisplayName}${Math.floor(Math.random() * 100)}`;
        } else { //纯数字
          singleFakeData[item.columnPropName] = Math.floor(Math.random() * 10000);
        }
      });
      return singleFakeData;
    }

  };

  //初始化数据
  initData = () => {
    const { currentEdit, sourceReportIdArray } = this.props;
    if (!currentEdit.id) {
      let propsData = deepCopy(currentEdit);
      return new Promise((resolve, reject) => {
        propsData.set = true;
        if (propsData.key === 'criteria') {
          propsData.sourceReportId = sourceReportIdArray.map(item => item)
            .join(',');
          this.setState({ editData: propsData }, () => {
            let params = {
              sourceReportIds: sourceReportIdArray.map(item => item)
                .join(','),
              criteriaFlag: true
            };
            this.getModalAttributeList(params)
              .then(() => {
                resolve();
              })
              .catch(() => {
                reject();
              });
          });
        } else {
          this.setState({ editData: propsData }, () => {
            resolve();
          });
        }
      });
    } else {
      return new Promise((resolve, reject) => {
        CustomReportService.getSingleChartDetailByItsOwnId(currentEdit.id)
          .then((res) => {
            if (res.status === 200) {
              this.setState({
                editData: Object.assign(currentEdit, res.data),
                CurrentSourceReportId: res.data.sourceReportId
              }, () => {
                if (res.data.sourceReportId) {
                  let params;
                  if (currentEdit.key === 'criteria') {
                    params = {
                      sourceReportIds: sourceReportIdArray.map(item => item)
                        .join(','),
                      criteriaFlag: true
                    };
                  } else {
                    params = {
                      sourceReportIds: res.data.sourceReportId
                    };
                  }
                  this.getModalAttributeList(params)
                    .then(() => {
                      resolve();
                    })
                    .catch(() => {
                      reject();
                    });
                  this.handleInitDimensionAndIndicator(res.data.reportChartDetails);
                }
              });
            }
          });
      });
    }
  };

  //获取所有数据模型
  getDataModalList = (keyword) => {
    let param = {
      key: keyword
    };
    return new Promise((resolve, reject) => {
      CustomReportService.getDataModalList(param)
        .then((res) => {
          if (res.status === 200) {
            this.setState({ dataModalList: res.data }, () => {
              this.handleModalListName(res.data);
              resolve();
            });
          }
        })
        .catch(() => {
          reject();
        });
    });
  };

  //处理所有数据模型 并按 id 排序
  handleModalListName = (dataModalList) => {
    const { sourceReportIdArray } = this.props;
    let ModalListNameArray = [];
    dataModalList.forEach((item) => {
      if (sourceReportIdArray.indexOf(item.id) !== -1) {
        ModalListNameArray.push(item);
      }
    });
    let result = sortByProperty(ModalListNameArray, 'id');
    this.setState({ ModalListNameArray: result });
  };

  //获取当前模型下 该 模型的所有 属性（字段）
  getModalAttributeList = (params) => {
    return new Promise((resolve, reject) => {
      CustomReportService.getAllAttributesByDataModalId(params)
        .then((res) => {
          if (res.status === 200) {
            this.setState({
              DataModalAttributes: sortByProperty(res.data, 'id'),
              loading: false,
              CurrentSourceReportId: params.sourceReportIds
            }, () => {
              resolve();
            });
          }
        })
        .catch(() => {
          this.setState({ loading: false }, () => {
            reject();
          });
        });
    });
  };

  //处理当 点击 左上角的返回
  onPageCanceled = () => {
    this.props.confirmOpened && this.props.confirmOpened(true);
    confirm({
      title: messages('basic-10.key99')/*警告*/,
      content: messages('basic-10.key100')/*退出会丢失已配置数据，确定退出？*/,
      okText: messages('common.ok')/*确定*/,
      cancelText: messages('common.cancel')/*取消*/,
      onOk: () => {
        this.props.confirmOpened && this.props.confirmOpened(false);
        this.props.onCancel && this.props.onCancel();
      },
      onCancel: () => {
        this.props.confirmOpened && this.props.confirmOpened(false);
      },
    });
  };

  // 渲染头信息
  renderPageHeader = () => {
    const { btnLoading, editData } = this.state;
    return <div className={'page-header'}>
      <div className="left">
        <Icon onClick={this.onPageCanceled} type="left"/>
        <span className={'report-name'}>
          {editData.key === 'criteria' ? messages('basic-10.key101')/*编辑筛选器*/ : (editData.name || messages('basic-10.key102')/*编辑单个图表*/)}
        </span>
      </div>
      <div className="right">
        <Button loading={btnLoading} type='primary'
                onClick={this.handleSingleSave}>{messages('common.save')/*保存*/}</Button>
      </div>
    </div>;
  };

  validateSave = () => {
    const { selectDimensionDataList, selectIndicatorDataList, selectShowDataList,
      selectDimensionRowDataList, editData } = this.state;
    let result = false;
    switch (editData.key) {
      case 'perspective':
        if (selectDimensionRowDataList.length !== 0 && selectIndicatorDataList.length !== 0) {
          result = true;
        } else {
          message.warn(messages('basic-10.key103')/*请添加维度(行)与指标*/)
        }
        break;
      case 'indicatrix':
        if (selectIndicatorDataList.length !== 0) {
          result = true;
        } else {
          message.warn(messages('basic-10.key104')/*请添指标*/)
        }
        break;
      case 'detail_list':
        if (selectShowDataList.length !== 0) {
          result = true;
        } else {
          message.warn(messages('basic-10.key105')/*请添显示字段*/)
        }
        break;
      case 'criteria':
        result = true;
        break;
      default:
        if (selectDimensionDataList.length !== 0 && selectIndicatorDataList.length !== 0) {
          result = true;
        } else {
          message.warn(messages('basic-10.key106')/*请添维度与指标*/)
        }
        break;
    }
    return result
  }

  //单个图表保存
  handleSingleSave = () => {
    const { editData, CurrentSourceReportId } = this.state;
    const { customReportData, sourceReportIdArray } = this.props;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {

        // 校验必填
        if (!this.validateSave()) {
          return
        }

        let data;
        this.setState({ btnLoading: true });
        if (editData.key === 'criteria') {
          this.defaultValueRef.validateFields((error, criteriaValues) => {
            if (!error) {
              data = {
                reportId: customReportData.id,
                reportChartDetails: this.handleWithDimensionAndIndicatorData(criteriaValues)
              };
            }
          });
        } else {
          data = {
            reportId: customReportData.id,
            reportChartDetails: this.handleWithDimensionAndIndicatorData()
          };
        }
        if (editData.key !== 'criteria') {
          data.name = values.name.name;
          data.i18n = { name: values.name.i18n };
          data.sourceReportId = CurrentSourceReportId;
        }
        data.chartType = editData.key;
        let updateData = Object.assign(editData, data);
        if (editData.key === 'criteria') { //筛选器创建的数据模型 默认取涉及到的其中一个模型id
          updateData.sourceReportId = sourceReportIdArray[0];
        }
        if (updateData.id) {
          CustomReportService.updateSingleChartDetail(updateData)
            .then((res) => {
              if (res.status === 200) {
                message.success(messages('basic-10.key107')/*保存成功*/);
                this.setState({ btnLoading: false });
                this.props.onCancel && this.props.onCancel(false, editData.key === 'criteria' ? null : updateData.id);
              }
            })
            .catch(() => {
              this.setState({ btnLoading: false });
            });
        } else {
          let sortAfterSave = updateData.currentSequence && (updateData.spliceIndex !== undefined);
          CustomReportService.addSingleChartByCustomReportId(updateData)
            .then((res) => {
              if (res.status === 200) {
                if (sortAfterSave) {
                  let sortArray = editData.currentSequence;
                  sortArray.splice(editData.spliceIndex, 0, res.data.id);
                  CustomReportService.sortChartsSequence(customReportData.id, sortArray)
                    .then((resp) => {
                      if (resp.status === 200) {
                        message.success(messages('basic-10.key107')/*保存成功*/);
                        this.setState({ btnLoading: false });
                        this.props.onCancel && this.props.onCancel();
                      }
                    })
                    .catch(() => {
                      this.setState({ btnLoading: false });
                    });
                } else {
                  message.success(messages('basic-10.key107')/*保存成功*/);
                  this.setState({ btnLoading: false });
                  this.props.onCancel && this.props.onCancel();
                }
              }
            })
            .catch(() => {
              this.setState({ btnLoading: false });
            });
        }

      }
    });
  };

  // 当 图表/明细表/筛选器  保存时， 从 维度/指标/显示字段/筛选条件 里拿到值 处理成 后端需要的数据结构
  handleWithDimensionAndIndicatorData = (defaultValues) => {
    const { selectDimensionDataList, selectIndicatorDataList, selectShowDataList, selectCriteriaDataList,
      selectDimensionRowDataList } = this.state;
    let dimensionList = [],
      dimensionRowList = [],
      indicatorList = [],
      showList = [],
      criteriaList = [],
      isPerspective = this.state.editData.key === 'perspective';
    let mapList = [
      { list: selectDimensionDataList, key: 'dimension', resultList: dimensionList, belongPosition: 'column' },
      { list: selectDimensionRowDataList, key: 'dimension', resultList: dimensionRowList, belongPosition: 'row' },
      { list: selectIndicatorDataList, key: 'indicator', resultList: indicatorList },
      { list: selectShowDataList, key: 'show', resultList: showList },
      { list: selectCriteriaDataList, key: 'criteria', resultList: criteriaList }
    ];
    mapList.forEach((singleItem) => {
      singleItem['list'].forEach((item) => {
        let single = {};
        let i18n = { fieldDisplayName: item.i18n.columnDisplayName || item.i18n.fieldDisplayName };
        single.sourceReportId = item.outId || item.reportId || item.sourceReportId;
        single.reportColumnId = item.reportColumnId || item.id;
        single.fieldType = singleItem.key;
        single.fieldDisplayName = item.columnDisplayName || item.fieldDisplayName;
        single.i18n = i18n;
        single.summaryWay = item.summaryWay;
        single.sequenceWay = item.sequenceWay;
        if (isPerspective)
          single.belongPosition = singleItem['belongPosition'];
        if (singleItem.key === 'criteria')
          single.defaultValue = handleDefaultValue(defaultValues[`${item.sourceReportId || item.reportId}_${item.criteriaPropName}`], item) || null;
        singleItem['resultList'].push(single);
      });
    });

    let resultArray = dimensionList.concat(indicatorList, showList, criteriaList, dimensionRowList);
    return resultArray;
  };

  // 处理 后端返回的 维度/指标/显示字段/筛选条件 数据结构  还原成 前端需要的数据结构 放回 维度/指标/显示字段/筛选条件
  handleInitDimensionAndIndicator = (data) => {
    let selectDimensionDataList = [],
      selectDimensionRowDataList = [],
      selectIndicatorDataList = [],
      selectShowDataList = [],
      selectCriteriaDataList = [];
    data.forEach((item, index) => {
      if (item.fieldType === 'dimension') {
        if (item.belongPosition === 'row') {
          selectDimensionRowDataList.push(item);
        } else {
          selectDimensionDataList.push(item);
        }
      } else if (item.fieldType === 'indicator') {
        selectIndicatorDataList.push(item);
      } else if (item.fieldType === 'show') {
        selectShowDataList.push(item);
      } else if (item.fieldType === 'criteria') {
        selectCriteriaDataList.push(item);
      }
    });
    this.setState({
      selectDimensionDataList,
      selectDimensionRowDataList,
      selectIndicatorDataList,
      selectShowDataList,
      selectCriteriaDataList
    }, () => {
      this.generateFakeData();
    });
  };

  //数据模型改变 逻辑处理
  handleModalChange = (value) => {
    const { selectDimensionDataList, selectIndicatorDataList, selectShowDataList, selectCriteriaDataList,
      selectDimensionRowDataList } = this.state;
    let length = selectDimensionDataList.length + selectIndicatorDataList.length +
      selectShowDataList.length + selectCriteriaDataList.length + selectDimensionRowDataList.length;
    if (length) {
      confirm({
        title: messages('basic-10.key99')/*警告*/,
        content: messages('basic-10.key108')/*切换数据模型会清空维度，指标与图形表联动，确定切换？*/,
        okText: messages('common.ok')/*确定*/,
        cancelText: messages('common.cancel')/*取消*/,
        onOk: () => {
          this.changeModal(value);
        },
        onCancel() {
        },
      });
    } else {
      this.changeModal(value);
    }
  };

  //数据模型改变 真正切换
  changeModal = (value) => {
    const { editData } = this.state;
    let copyData = deepCopy(editData);
    copyData.reportChartLinkages = [];
    copyData.allLinkage = false;
    this.setState({
      loading: true,
      selectDimensionRowDataList: [],
      selectDimensionDataList: [],
      selectIndicatorDataList: [],
      selectShowDataList: [],
      selectCriteriaDataList: [],
      linkableList: [],
      editData: copyData
    });
    let params = {
      sourceReportIds: value
    };
    this.getModalAttributeList(params);
    this.getLinkableList(value);
  };

  // 渲染可拖拽数据list
  renderDataList = () => {
    const { DataModalAttributes, ModalListNameArray, SearchKeyWord, hoverItem } = this.state;
    if (DataModalAttributes && DataModalAttributes.length) {
      return (
        <div className='attributes-list'>
          {DataModalAttributes.map((modal) => {
            return (
              <div className="single-modal">
                {DataModalAttributes.length > 1 &&
                <div className="modal-title" id={`custom-modal-title-${modal.id}`}>
                  {ModalListNameArray.map((name) => {
                    if (name.id === modal.id) {
                      return name.reportName + '：';
                    }
                  })}
                </div>}
                <div className="modal-attr-list">
                  {/*后端数据有些在 reportColumnCustomizedDTOList  有些在 reportColumnDTOList*/}
                  {
                    (modal.reportColumnCustomizedDTOList || modal.reportColumnDTOList) &&
                    (modal.reportColumnCustomizedDTOList || modal.reportColumnDTOList)
                      .filter((item)=>{return item.columnDisplayName.indexOf(SearchKeyWord) !== -1}).map(widget =>
                      <DataDragItem
                        onItemClick={(item) => {
                          this.handleItemClick(item);
                        }}
                        onDragEnd={this.onDragEnd}
                        keyWord={SearchKeyWord}
                        hoverItem={hoverItem}
                        widget={widget}
                        id={`custom-modal-data-${widget.id}`}
                        key={widget.id}
                      />
                    )
                  }
                  {SearchKeyWord.length !== 0 &&
                  (modal.reportColumnCustomizedDTOList || modal.reportColumnDTOList) &&
                  (modal.reportColumnCustomizedDTOList || modal.reportColumnDTOList)
                    .filter((item)=>{return item.columnDisplayName.indexOf(SearchKeyWord) !== -1}).length === 0 &&
                  <div className='search-no-data'>{messages('common.no.data')/*无数据*/}</div>
                  }
                </div>
              </div>
            );
          })}
        </div>
      );
    } else {
      return null
    }
  };

  // 同样 模型的属性 可以 拖动到 维度/指标/显示字段/筛选条件  也可以点击 添加 前提是 激活对应的 维度/指标/显示字段/筛选条件
  handleItemClick = (item) => {
    const { focusBox } = this.state;
    if (item.dataType === 'date' && focusBox === 'indicator') {
      message.warn(messages('basic-10.key109')/*日期不能作为指标*/);
    } else {
      if (!focusBox) {
        return;
      } else {
        let handledData = this.handleInitSetting(item);
        if (focusBox === 'dimension') {
          if (this.state.selectDimensionDataList.length < 1 || this.state.editData.key === 'perspective') {
            if (this.state.selectDimensionDataList.length < 5) {
              if (!this.validateDuplicate(item, 'dimension')) {
                const { selectDimensionDataList } = this.state;
                let copyData = deepCopy(selectDimensionDataList);
                copyData.push(handledData);
                this.setState({ selectDimensionDataList: copyData }, () => {
                  this.generateFakeData(true);
                });
              } else {
                message.warn(messages('basic-10.key110')/*已有该字段，不能重复添加*/);
              }
            } else {
              message.warn(messages('basic-10.key111',{arg1: GraphicMap[this.state.editData.key]})/*{arg1}维度(列)不能大于5*/);
            }
          } else {
            message.warn(messages('basic-10.key112',{arg1: GraphicMap[this.state.editData.key]})/*{arg1}维度不能大于1*/);
          }
        } else if (focusBox === 'dimensionRow') {
          if (!this.validateDuplicate(item, 'dimensionRow')) {
            const { selectDimensionRowDataList } = this.state;
            let copyData = deepCopy(selectDimensionRowDataList);
            copyData.push(handledData);
            this.setState({ selectDimensionRowDataList: copyData }, () => {
              this.generateFakeData(true);
            });
          } else {
            message.warn(messages('basic-10.key110')/*已有该字段，不能重复添加*/);
          }
        } else if (focusBox === 'indicator') {
          if (this.state.editData.key === 'pie' || this.state.editData.key === 'indicatrix') {
            if (this.state.selectIndicatorDataList.length < 1) {
              if (!this.validateDuplicate(item, 'indicator')) {
                const { selectIndicatorDataList } = this.state;
                let copyData = deepCopy(selectIndicatorDataList);
                copyData.push(handledData);
                this.setState({ selectIndicatorDataList: copyData }, () => {
                  this.generateFakeData(true);
                });
              } else {
                message.warn(messages('basic-10.key110')/*已有该字段，不能重复添加*/);
              }
            } else {
              message.warn(messages('basic-10.key113',{arg1: GraphicMap[this.state.editData.key]})/*{arg1}指标不能大于1*/);
            }
          } else {
            if (!this.validateDuplicate(item, 'indicator')) {
              const { selectIndicatorDataList } = this.state;
              let copyData = deepCopy(selectIndicatorDataList);
              copyData.push(handledData);
              this.setState({ selectIndicatorDataList: copyData }, () => {
                this.generateFakeData(true);
              });
            } else {
              message.warn(messages('basic-10.key110')/*已有该字段，不能重复添加*/);
            }
          }
        } else if (focusBox === 'show') {
          if (!this.validateDuplicate(item, 'show')) {
            const { selectShowDataList } = this.state;
            let copyData = deepCopy(selectShowDataList);
            copyData.push(handledData);
            this.setState({ selectShowDataList: copyData }, () => {
              this.generateFakeData(true);
            });
          } else {
            message.warn(messages('basic-10.key110')/*已有该字段，不能重复添加*/);
          }
        } else if (focusBox === 'criteria') {
          if (!this.validateDuplicate(item, 'criteria')) {
            const { selectCriteriaDataList } = this.state;
            let copyData = deepCopy(selectCriteriaDataList);
            copyData.push(handledData);
            this.setState({ selectCriteriaDataList: copyData }, () => {
              this.generateFakeData(true);
            });
          } else {
            message.warn(messages('basic-10.key110')/*已有该字段，不能重复添加*/);
          }
        }
      }
    }
  };

  //校验 每个 维度/指标/显示字段/筛选条件  里 是否有重复的 属性   放置新属性时 校验
  validateDuplicate = (item, key) => {
    let result = false;
    let itemResourceId = item.sourceReportId || item.reportId;
    let itemColumnId = item.reportColumnId || item.id;
    let isPerspective = this.state.editData.key === 'perspective';
    const { selectDimensionDataList, selectDimensionRowDataList, selectIndicatorDataList } = this.state;
    switch (key) {
      case 'dimension':
        if (isPerspective) {
          result = judgeRowAndCol();
        } else {
          result = judgeDimensionAndIndex();
        }
        break;
      case 'dimensionRow':
        result = judgeRowAndCol();
        break;
      case 'indicator':
        result = judgeDimensionAndIndex();
        break;
      case 'show':
        const { selectShowDataList } = this.state;
        selectShowDataList.forEach((widget) => {
          if (((widget.sourceReportId || widget.reportId) === itemResourceId) && ((widget.reportColumnId || widget.id) === itemColumnId)) {
            result = true;
          }
        });
        break;
      case 'criteria':
        const { selectCriteriaDataList } = this.state;
        selectCriteriaDataList.forEach((widget) => {
          if (((widget.sourceReportId || widget.reportId) === itemResourceId) && ((widget.reportColumnId || widget.id) === itemColumnId)) {
            result = true;
          }
        });
        break;
    }
    function judgeRowAndCol() {
      let resultJudge = false;
      selectDimensionDataList.forEach((widget) => {
        if (((widget.sourceReportId || widget.reportId) === itemResourceId) && ((widget.reportColumnId || widget.id) === itemColumnId)) {
          resultJudge = true;
        }
      });
      selectDimensionRowDataList.forEach((widget) => {
        if (((widget.sourceReportId || widget.reportId) === itemResourceId) && ((widget.reportColumnId || widget.id) === itemColumnId)) {
          resultJudge = true;
        }
      });
      selectIndicatorDataList.forEach((widget) => {
        if (((widget.sourceReportId || widget.reportId) === itemResourceId) && ((widget.reportColumnId || widget.id) === itemColumnId)) {
          resultJudge = true;
        }
      });
      return resultJudge
    }
    function judgeDimensionAndIndex() {
      let resultJudge = false;
      selectIndicatorDataList.forEach((widget) => {
        if (((widget.sourceReportId || widget.reportId) === itemResourceId) && ((widget.reportColumnId || widget.id) === itemColumnId)) {
          resultJudge = true;
        }
      });
      selectDimensionDataList.forEach((widget) => {
        if (((widget.sourceReportId || widget.reportId) === itemResourceId) && ((widget.reportColumnId || widget.id) === itemColumnId)) {
          resultJudge = true;
        }
      });
      return resultJudge
    }
    return result;
  };

  //处理 属性 放置在维度
  handleDimensionDrop = (item, index) => {
    if (this.state.selectDimensionDataList.length < 1 || this.state.editData.key === 'perspective') {
      if (this.state.selectDimensionDataList.length < 5) {
        if (!this.validateDuplicate(item, 'dimension')) {
          const { selectDimensionDataList } = this.state;
          let handledData = this.handleInitSetting(item);
          selectDimensionDataList.splice(index, 0, handledData);
          this.setState({ selectDimensionDataList }, () => {
            this.generateFakeData();
          });
        } else {
          message.warn(messages('basic-10.key110')/*已有该字段，不能重复添加*/);
        }
      } else {
        message.warn(messages('basic-10.key111',{arg1: GraphicMap[this.state.editData.key]})/*{arg1}维度(列)不能大于5*/);
      }
    } else {
      message.warn(messages('basic-10.key112',{arg1: GraphicMap[this.state.editData.key]})/*{arg1}维度不能大于1*/);
    }
  };

  handleDimensionRowDrop = (item, index) => {
    if (!this.validateDuplicate(item, 'dimensionRow')) {
      const { selectDimensionRowDataList } = this.state;
      let handledData = this.handleInitSetting(item);
      selectDimensionRowDataList.splice(index, 0, handledData);
      this.setState({ selectDimensionRowDataList }, () => {
        this.generateFakeData();
      });
    } else {
      message.warn(messages('basic-10.key110')/*已有该字段，不能重复添加*/);
    }
  }

  //拖动已放置的数据  那就索性直接删除吧……  放的时候 再 正常放置
  handleOnDragDroppedItem = (item, key) => {
    if (['perspective', 'detail_list'].indexOf(this.state.editData.key) !== -1) {
      this.setState({noUpdate: true})
    }
    this.deleteItem(item, key);
  };

  //处理 属性 放置在指标
  handleIndicatorDrop = (item, index) => {
    if (item.dataType === 'date') {
      message.warn(messages('basic-10.key109')/*日期不能作为指标*/);
    } else {
      if (this.state.editData.key === 'pie' || this.state.editData.key === 'indicatrix') {
        if (this.state.selectIndicatorDataList.length < 1) {
          if (!this.validateDuplicate(item, 'indicator')) {
            const { selectIndicatorDataList } = this.state;
            let handledData = this.handleInitSetting(item);
            selectIndicatorDataList.splice(index, 0, handledData);
            this.setState({ selectIndicatorDataList }, () => {
              this.generateFakeData();
            });
          } else {
            message.warn(messages('basic-10.key110')/*已有该字段，不能重复添加*/);
          }
        } else {
          message.warn(messages('basic-10.key113',{arg1: GraphicMap[this.state.editData.key]})/*{arg1}指标不能大于1*/);
        }
      } else {
        if (!this.validateDuplicate(item, 'indicator')) {
          const { selectIndicatorDataList } = this.state;
          let handledData = this.handleInitSetting(item);
          selectIndicatorDataList.splice(index, 0, handledData);
          this.setState({ selectIndicatorDataList }, () => {
            this.generateFakeData();
          });
        } else {
          message.warn(messages('basic-10.key110')/*已有该字段，不能重复添加*/);
        }
      }
    }
  };

  //处理 属性 放置在显示字段
  handleShowDrop = (item, index) => {
    if (!this.validateDuplicate(item, 'show')) {
      const { selectShowDataList } = this.state;
      let handledData = this.handleInitSetting(item);
      selectShowDataList.splice(index, 0, handledData);
      this.setState({ selectShowDataList }, () => {
        this.generateFakeData();
      });
    } else {
      message.warn(messages('basic-10.key110')/*已有该字段，不能重复添加*/);
    }
  };

  //处理 属性 放置在筛选条件
  handleCriteriaDrop = (item, index) => {
    if (!this.validateDuplicate(item, 'criteria')) {
      const { selectCriteriaDataList } = this.state;
      let handledData = this.handleInitSetting(item);
      selectCriteriaDataList.splice(index, 0, handledData);
      this.setState({ selectCriteriaDataList }, () => {
        this.generateFakeData();
      });
    } else {
      message.warn(messages('basic-10.key110')/*已有该字段，不能重复添加*/);
    }
  };

  //处理数据放置时的初始数据   排序：默认排序   计算：数字数据为 求和      非数字数据 为  计数
  handleInitSetting = (item) => {
    let copyData = deepCopy(item);
    copyData.sequenceWay = 'default_order';
    if (!(['bigdecimal', 'number'].indexOf(item.dataType) !== -1)) {
      copyData.summaryWay = 'count';
    } else {
      copyData.summaryWay = 'sum';
    }
    return copyData;
  };

  //改变当前图表的 数据展示模式  逻辑处理
  changeGraphic = (item) => {
    const { editData } = this.state;
    let copyData = deepCopy(editData);
    let haveData = (editData.reportChartLinkages && editData.reportChartLinkages.length > 0) || editData.allLinkage;
    let notSupportGraphic = ['radar', 'indicatrix'].indexOf(item.key) !== -1;
    if (haveData && notSupportGraphic) {
      confirm({
        title: messages('basic-10.key99')/*警告*/,
        content: messages('basic-10.key114',{arg1: GraphicMap[editData.key],arg2: GraphicMap[item.key]})/*从【{arg1}】切换到【{arg2}】会清空图形表联动，确定切换？*/,
        okText: messages('common.ok')/*确定*/,
        cancelText: messages('common.cancel')/*取消*/,
        onOk: () => {
          this.doChangeGraphic(copyData, item);
        },
        onCancel() {
        },
      });
    } else if (editData.key === 'perspective') {
      let hasData = (this.state.selectIndicatorDataList.length || this.state.selectDimensionDataList.length || this.state.selectDimensionRowDataList.length);
      if (hasData) {
        confirm({
          title: messages('basic-10.key99')/*警告*/,
          content: messages('basic-10.key115',{arg1: GraphicMap[editData.key],arg2: GraphicMap[item.key]})/*从【{arg1}】切换到【{arg2}】会清空纬度(行)，纬度(列)以及指标，确定切换？*/,
          okText: messages('common.ok')/*确定*/,
          cancelText: messages('common.cancel')/*取消*/,
          onOk: () => {
            this.setState({
              selectIndicatorDataList: [],
              selectDimensionDataList: [],
              selectDimensionRowDataList: []
            })
            this.doChangeGraphic(copyData, item);
          },
          onCancel() {
          },
        });
      } else {
        this.doChangeGraphic(copyData, item);
      }
    } else {
      this.doChangeGraphic(copyData, item);
    }

  };

  //改变当前图表的 数据展示模式  真正切换
  doChangeGraphic = (copyData, item) => {
    copyData.key = item.key;
    copyData.reportChartLinkages = [];
    copyData.allLinkage = false;
    if (['broken_line', 'area'].indexOf(item.key) !== -1) {
      copyData.showLegendLocation = 'up';
    } else if (['radar', 'pie'].indexOf(item.key) !== -1) {
      copyData.showLegendLocation = 'right';
    } else {
      copyData.showLegendLocation = undefined;
    }
    this.setState({ editData: copyData });
  };

  //渲染 可以 选择 图表类型
  renderGraphic = () => {
    const { editData, selectIndicatorDataList } = this.state;
    let pieClickable = selectIndicatorDataList.length <= 1;

    return (
      graphList.map((item) => {
        let isPieOrIndicate = item.key === 'pie' || item.key === 'indicatrix';

        return (
          <Popover content={item.desc}>
            <div
              className={`graphic-item-content ${item.key === editData.key ? 'active' : ''} ${isPieOrIndicate ? `${!pieClickable && 'pieDisable'}` : ''}`}
              onClick={() => {
                (!isPieOrIndicate || pieClickable) && this.changeGraphic(item);
              }}
            >
              <div className="img-wrapper">
                <img onMouseDown={e => e.preventDefault()} className="img" src={iconMap[item.key]}
                     alt={item.chartName}/>
              </div>
              <div className={'menu-title'}>{item.chartName}</div>
            </div>
          </Popover>
        );
      })
    );
  };

  //切换 指标图  字体大小
  changeFontSize = (item) => {
    const { editData } = this.state;
    let copyData = deepCopy(editData);
    copyData.style = item.key;
    this.setState({ editData: copyData });
  };

  //渲染指标图  字体大小选择项
  renderFontSizeOptions = () => {
    const { editData } = this.state;

    return (
      fontSizeOptions.map((item) => {
        return (
          <div
            onClick={() => {
              this.changeFontSize(item);
            }}
            className={`font-size-box font-${item.fontSize} ${editData.style === item.key ? 'active' : ''}`}
          >
            123
          </div>
        );
      })
    );
  };

  // 处理 所有 图表明细设置 的 checkbox
  CheckboxChange = (e, field) => {
    let checked = e.target.checked;
    const { editData } = this.state;
    let copyData = deepCopy(editData);
    switch (field) {
      case 'narrowRangeFlag':
        copyData.narrowRangeFlag = checked;
        this.setState({ editData: copyData }, ()=>{
          this.generateFakeData();
          this.GraphicRef.onMountCharts.ref.chart.clear();
        });
        break;
      case 'limitNum':
        if (checked) {
          copyData.limitNum = 1;
          this.setState({ editData: copyData });
        } else {
          copyData.limitNum = undefined;
          this.setState({ editData: copyData });
        }
        break;
      case 'fixedColumnsNum':
        if (checked) {
          copyData.fixedColumnsNum = 1;
          this.setState({ editData: copyData });
        } else {
          copyData.fixedColumnsNum = undefined;
          this.setState({ editData: copyData });
        }
        break;
      case 'showLabelFlag':
        copyData.showLabelFlag = checked;
        this.setState({ editData: copyData });
        break;
      case 'showDimensionFlag':
        copyData.showDimensionFlag = checked;
        this.setState({ editData: copyData });
        break;
      case 'showIndicatorFlag':
        copyData.showIndicatorFlag = checked;
        this.setState({ editData: copyData });
        break;
      case 'showPercentFlag':
        copyData.showPercentFlag = checked;
        this.setState({ editData: copyData });
        break;
      case 'operateType':
        copyData.operateType = checked.toString();
        this.setState({ editData: copyData });
        break;
      case 'showLegendLocation':
        if (checked) {
          if (['broken_line', 'area'].indexOf(editData.key) !== -1) {
            copyData.showLegendLocation = 'up';
          } else if (['radar', 'pie'].indexOf(editData.key) !== -1) {
            copyData.showLegendLocation = 'right';
          } else {
            copyData.showLegendLocation = 'false';
          }
          this.setState({ editData: copyData });
        } else {
          copyData.showLegendLocation = 'false';
          this.setState({ editData: copyData });
        }
        break;
    }
  };

  //处理 显示前N条数据 改变
  limitNumChange = (value, isLimit) => {
    const { editData } = this.state;
    let copyData = deepCopy(editData);
    if (isLimit) {
      copyData.limitNum = value;
      this.setState({ editData: copyData });
    } else {
      copyData.fixedColumnsNum = value;
      this.setState({ editData: copyData });
    }
  };

  //处理 图例是否展示/图例位置 改变
  onLocationChange = (value) => {
    const { editData } = this.state;
    let copyData = deepCopy(editData);
    copyData.showLegendLocation = value;
    this.setState({ editData: copyData });
  };

  //渲染图表 设置详情
  renderDisplaySetting = () => {
    const { editData } = this.state;
    return (
      <div className='display-setting-list'>
        {editData.key !== 'detail_list' && <div className='single-check'>
          <Checkbox checked={editData.limitNum} onChange={(e) => {
            this.CheckboxChange(e, 'limitNum');
          }}>
            {messages('basic-10.key116')/*显示前*/}
            <InputNumber min={1} value={editData.limitNum} onChange={(value) => {
              this.limitNumChange(value, true);
            }}
                         style={{ margin: '0 8px' }}/>
            {messages('basic-10.key117')/*条数据*/}
          </Checkbox>
        </div>}
        {['histogram', 'horizon-histogram', 'area', 'broken_line'].indexOf(editData.key) !== -1 &&
        <div className='single-check'>
          <Checkbox checked={editData.narrowRangeFlag} onChange={(e) => {this.CheckboxChange(e, 'narrowRangeFlag')}}>
            {messages('basic-10.key118')/*启用数据缩放*/}
          </Checkbox>
        </div>}
        {editData.key === 'detail_list' && <div className='single-check'>
          <Checkbox checked={editData.fixedColumnsNum} onChange={(e) => {
            this.CheckboxChange(e, 'fixedColumnsNum');
          }}>
            {messages('basic-10.key119')/*固定前*/}
            <InputNumber min={1} value={editData.fixedColumnsNum} onChange={(value) => {
              this.limitNumChange(value, false);
            }}
                         style={{ margin: '0 8px' }}/>
            {messages('basic-10.key120')/*列数据*/}
          </Checkbox>
        </div>}
        {['histogram', 'horizon-histogram', 'area', 'broken_line', 'radar'].indexOf(editData.key) !== -1 &&
        <div className='single-check'>
          <Checkbox checked={editData.showLabelFlag} onChange={(e) => {
            this.CheckboxChange(e, 'showLabelFlag');
          }}>
            {messages('basic-10.key121')/*显示数据标签*/}
          </Checkbox>
        </div>
        }
        {['pie'].indexOf(editData.key) !== -1 &&
        <div className='single-check'>
          <Checkbox checked={editData.showDimensionFlag} onChange={(e) => {
            this.CheckboxChange(e, 'showDimensionFlag');
          }}>
            {messages('basic-10.key122')/*显示维度值*/}
          </Checkbox>
        </div>
        }
        {['pie'].indexOf(editData.key) !== -1 &&
        <div className='single-check'>
          <Checkbox checked={editData.showIndicatorFlag} onChange={(e) => {
            this.CheckboxChange(e, 'showIndicatorFlag');
          }}>
            {messages('basic-10.key123')/*显示指标值*/}
          </Checkbox>
        </div>
        }
        {['pie'].indexOf(editData.key) !== -1 &&
        <div className='single-check'>
          <Checkbox checked={editData.showPercentFlag} onChange={(e) => {
            this.CheckboxChange(e, 'showPercentFlag');
          }}>
            {messages('basic-10.key124')/*显示百分比*/}
          </Checkbox>
        </div>
        }
        {!(['indicatrix', 'histogram', 'horizon-histogram', 'detail_list'].indexOf(editData.key) !== -1) &&
        <div className='single-check'>
          <Checkbox checked={editData.showLegendLocation !== 'false'} onChange={(e) => {
            this.CheckboxChange(e, 'showLegendLocation');
          }}>
            {messages('basic-10.key125')/*显示图例在*/}
            <Select
              value={editData.showLegendLocation === 'false' ? undefined : editData.showLegendLocation}
              onChange={this.onLocationChange}
              style={{ minWidth: 80, marginLeft: 8 }}
            >
              {['broken_line', 'area', 'radar', 'pie'].indexOf(editData.key) !== -1 &&
              <Option value="up">{messages('basic-10.key126')/*上*/}</Option>}
              {['radar', 'pie', 'broken_line', 'area'].indexOf(editData.key) !== -1 &&
              <Option value="left">{messages('basic-10.key127')/*左*/}</Option>}
              {['radar', 'pie', 'broken_line', 'area'].indexOf(editData.key) !== -1 &&
              <Option value="right">{messages('basic-10.key128')/*右*/}</Option>}
              {['radar', 'pie', 'broken_line', 'area'].indexOf(editData.key) !== -1 &&
              <Option value="down">{messages('basic-10.key129')/*下*/}</Option>}
            </Select></Checkbox>
        </div>
        }
      </div>
    );
  };

  //渲染 明细表 是否可以 允许导出
  renderOperateSetting = () => {
    const { editData } = this.state;
    return (
      <div className='display-setting-list'>
        {['detail_list', 'perspective'].indexOf(editData.key) !== -1 &&
        <div className='single-check'>
          <Checkbox checked={editData.operateType !== 'false' && editData.operateType !== null}
                    onChange={(e) => {
                      this.CheckboxChange(e, 'operateType');
                    }}>
            {messages('basic-10.key130')/*允许导出操作*/}
          </Checkbox>
        </div>
        }
      </div>
    );
  };

  //渲染 筛选器 默认值
  renderDefaultValueList = () => {
    const { selectCriteriaDataList } = this.state;
    const searchForm = UniversalReportService.searchFormFactory({
      context: this,
      list: selectCriteriaDataList.map((item) => {
        return {
          criteriaCode: item.criteriaCode,
          criteriaName: item.fieldDisplayName || item.columnDisplayName,
          criteriaPropName: `${item.sourceReportId || item.reportId}_${item.criteriaPropName}`,
          defaultValue: item.defaultValue
        };
      })
    });
    return (
      <div className='default-value-list'>
        <DefaultValue
          getForm={ref => this.defaultValueRef = ref}
          pinnedList={searchForm.map(item => item.id)}
          searchForm={searchForm}
          notLoadWhenMount
        />
      </div>
    );
  };

  // 处理 勾选 图表联动全部
  onCheckAllLink = (e) => {
    const { editData, linkableList } = this.state;
    let copyData = deepCopy(editData);
    copyData.allLinkage = e.target.checked;
    if (e.target.checked) {
      copyData.reportChartLinkages = linkableList.map((item) => {
        return { targetReportChartId: item.id };
      });
    } else {
      copyData.reportChartLinkages = [];
    }
    this.setState({ editData: copyData });
  };

  // 处理 勾选 图表联动
  linkagesChange = (checkedList) => {
    const { editData } = this.state;
    let copyData = deepCopy(editData);
    copyData.allLinkage = false;
    copyData.reportChartLinkages = checkedList.map((item) => {
      return { targetReportChartId: item };
    });
    this.setState({ editData: copyData });
  };

  //渲染 可 联动图表
  renderLinkableCharts = () => {
    const { CurrentSourceReportId, linkableLoading, linkableList, editData } = this.state;
    let options = linkableList.map((item) => {
      return { label: item.name, value: item.id };
    });
    let value = editData.allLinkage ? linkableList.map(item => item.id) : (editData.reportChartLinkages || []).map(item => item.targetReportChartId);
    return (
      CurrentSourceReportId && linkableList && linkableList.length ?
        <Spin spinning={linkableLoading}>
          <div className='linkable-checkbox-wrapper'>
            <Checkbox
              onChange={this.onCheckAllLink}
              checked={editData.allLinkage}
            >
              {messages('basic-10.key131')/*全选*/}
            </Checkbox>
            <Checkbox.Group
              options={options}
              value={value}
              onChange={this.linkagesChange}
            />
          </div>
        </Spin>
        : null
    );
  };

  //处理 维度/指标/显示字段/筛选条件  属性的删除
  deleteItem = (item, key) => {
    switch (key) {
      case 'dimension':
        const { selectDimensionDataList } = this.state;
        let copyData1 = deepCopy(selectDimensionDataList);
        copyData1 = removeArrayItemByKey(copyData1, item, 'id');
        this.setState({ selectDimensionDataList: copyData1 });
        break;
      case 'dimensionRow':
        const { selectDimensionRowDataList } = this.state;
        let copyData5 = deepCopy(selectDimensionRowDataList);
        copyData5 = removeArrayItemByKey(copyData5, item, 'id');
        this.setState({ selectDimensionRowDataList: copyData5 });
        break;
      case 'indicator':
        const { selectIndicatorDataList } = this.state;
        let copyData2 = deepCopy(selectIndicatorDataList);
        copyData2 = removeArrayItemByKey(copyData2, item, 'id');
        this.setState({ selectIndicatorDataList: copyData2 });
        break;
      case 'show':
        const { selectShowDataList } = this.state;
        let copyData3 = deepCopy(selectShowDataList);
        copyData3 = removeArrayItemByKey(copyData3, item, 'id');
        this.setState({ selectShowDataList: copyData3 });
        break;
      case 'criteria':
        const { selectCriteriaDataList } = this.state;
        let copyData4 = deepCopy(selectCriteriaDataList);
        copyData4 = removeArrayItemByKey(copyData4, item, 'id');
        this.setState({ selectCriteriaDataList: copyData4 });
        break;
    }
  };

  handleItemMouseOver = (item) => {
    this.setState({hoverItem: item});
  }

  handleOnItemClick = (item) => {
    let y = document.getElementById(`custom-modal-data-${item.reportColumnId || item.id}`).offsetTop;
    scrollToMyDestination(this.dataListBoxRef, y);
  }

  handleItemMouseLeave = () => {
    this.handleItemMouseOver.cancel();
    this.setState({hoverItem: {}});
  }

  //处理 维度/指标/显示字段/筛选条件 单独属性 展示名 多语言 的变动
  onSaveI18n = (i18nItem, widget, key) => {
    switch (key) {
      case 'dimension':
        const { selectDimensionDataList } = this.state;
        let copyData1 = deepCopy(selectDimensionDataList);
        selectDimensionDataList.forEach((item, index) => {
          if (item.id === widget.id) {
            if (copyData1[index].reportColumnId) {
              copyData1[index].fieldDisplayName = i18nItem.name;
              copyData1[index].i18n.fieldDisplayName = i18nItem.i18n;
            } else {
              copyData1[index].columnDisplayName = i18nItem.name;
              copyData1[index].i18n.columnDisplayName = i18nItem.i18n;
            }
          }
        });
        this.setState({ selectDimensionDataList: copyData1 });
        break;
      case 'dimensionRow':
        const { selectDimensionRowDataList } = this.state;
        let copyData5 = deepCopy(selectDimensionRowDataList);
        selectDimensionRowDataList.forEach((item, index) => {
          if (item.id === widget.id) {
            if (copyData5[index].reportColumnId) {
              copyData5[index].fieldDisplayName = i18nItem.name;
              copyData5[index].i18n.fieldDisplayName = i18nItem.i18n;
            } else {
              copyData5[index].columnDisplayName = i18nItem.name;
              copyData5[index].i18n.columnDisplayName = i18nItem.i18n;
            }
          }
        });
        this.setState({ selectDimensionRowDataList: copyData5 });
        break;
      case 'indicator':
        const { selectIndicatorDataList } = this.state;
        let copyData2 = deepCopy(selectIndicatorDataList);
        selectIndicatorDataList.forEach((item, index) => {
          if (item.id === widget.id) {
            if (copyData2[index].reportColumnId) {
              copyData2[index].fieldDisplayName = i18nItem.name;
              copyData2[index].i18n.fieldDisplayName = i18nItem.i18n;
            } else {
              copyData2[index].columnDisplayName = i18nItem.name;
              copyData2[index].i18n.columnDisplayName = i18nItem.i18n;
            }
          }
        });
        this.setState({ selectIndicatorDataList: copyData2 });
        break;
      case 'show':
        const { selectShowDataList } = this.state;
        let copyData3 = deepCopy(selectShowDataList);
        selectShowDataList.forEach((item, index) => {
          if (item.id === widget.id) {
            if (copyData3[index].reportColumnId) {
              copyData3[index].fieldDisplayName = i18nItem.name;
              copyData3[index].i18n.fieldDisplayName = i18nItem.i18n;
            } else {
              copyData3[index].columnDisplayName = i18nItem.name;
              copyData3[index].i18n.columnDisplayName = i18nItem.i18n;
            }
          }
        });
        this.setState({ selectShowDataList: copyData3 });
        break;
      case 'criteria':
        const { selectCriteriaDataList } = this.state;
        let copyData4 = deepCopy(selectCriteriaDataList);
        selectCriteriaDataList.forEach((item, index) => {
          if (item.id === widget.id) {
            if (copyData4[index].reportColumnId) {
              copyData4[index].fieldDisplayName = i18nItem.name;
              copyData4[index].i18n.fieldDisplayName = i18nItem.i18n;
            } else {
              copyData4[index].columnDisplayName = i18nItem.name;
              copyData4[index].i18n.columnDisplayName = i18nItem.i18n;
            }
          }
        });
        this.setState({ selectCriteriaDataList: copyData4 });
        break;
    }
  };

  // 处理 维度/指标/显示字段/筛选条件  单独属性  排序方式 汇总计算方式 的 改变
  onChangeDataStatus = (key, widget, isSequence, isShowList) => {
    const { selectIndicatorDataList, selectShowDataList } = this.state;
    if (isShowList) {
      let copyData = deepCopy(selectShowDataList);
      selectShowDataList.forEach((item, index) => {
        if (item.id === widget.id) {
          if (isSequence) {
            copyData[index].sequenceWay = key;
          } else {
            copyData[index].summaryWay = key;
          }
        }
      });
      this.setState({ selectShowDataList: copyData });
    } else {
      let copyData = deepCopy(selectIndicatorDataList);
      selectIndicatorDataList.forEach((item, index) => {
        if (item.id === widget.id) {
          if (isSequence) {
            copyData[index].sequenceWay = key;
          } else {
            copyData[index].summaryWay = key;
          }
        }
      });
      this.setState({ selectIndicatorDataList: copyData });
    }
  };

  // 维度/指标/显示字段/筛选条件 box 的 聚焦/失焦
  focusBox = (key) => {
    const { focusBox } = this.state;
    if (key === focusBox) {
      this.setState({ focusBox: '' });
    } else {
      this.setState({ focusBox: key });
    }
  };

  //右边基本信息 以后会 引入其他tab   tab切换
  onTabChange = (e) => {
  };

  //编辑筛选器时  多个模型 以tab 形式展示在
  onReportNameClick = (id) => {
    let y = document.getElementById(`custom-modal-title-${id}`).offsetTop;
    scrollToMyDestination(this.dataListBoxRef, y);
  };

  //编辑筛选器时  渲染所有图表涉及到的数据模型
  renderAllModalList = () => {
    const { ModalListNameArray } = this.state;
    return (
      <div className="all-modal-tab">
        <Tabs size="small" onChange={this.onReportNameClick}>
          {ModalListNameArray.map((item) => {
            return (
              <TabPane tab={item.reportName} key={item.id}/>
            );
          })}
        </Tabs>
      </div>
    );
  };

  handleSearchModalAttributes = (e) => {
    this.setState({SearchKeyWord: e || ''})
  }

  modalSearchOnChange = (e) => {
    e.persist();
    this.handleSearchModalAttributes(e.target.value)
  }

  render() {
    const {
      loading, selectDimensionDataList, selectDimensionRowDataList, selectIndicatorDataList, dataModalList,
      editData, CurrentSourceReportId, DataModalAttributes, focusBox, fakeDataLength, fakeData,
      selectShowDataList, selectCriteriaDataList, loadingAll, linkableList, noUpdate
    } = this.state;
    const { getFieldDecorator } = this.props.form;
    const { customReportData } = this.props;
    const { code } = this.props.language;

    const dropMap = {
      'dimensionRow': this.handleDimensionRowDrop,
      'dimension': this.handleDimensionDrop,
      'indicator': this.handleIndicatorDrop,
      'criteria': this.handleCriteriaDrop,
      'show': this.handleShowDrop
    }

    const ListMap = {
      'dimensionRow': selectDimensionRowDataList,
      'dimension': selectDimensionDataList,
      'indicator': selectIndicatorDataList,
      'criteria': selectCriteriaDataList,
      'show': selectShowDataList
    }

    return (
      <div className='edit-custom-report'>
        <Spin spinning={loadingAll}>
          <div style={{ height: '100vh', overflow: 'auto' }}>
            {this.renderPageHeader()}
            <Layout className={'page-body'}>
              <Content>
                <div className="data-box">
                  <div className={`choose-box ${editData.key !== 'criteria' && 'padding-bottom'}`}>
                    <div className="choose-flex-box">
                      {editData.key !== 'criteria' &&
                      <div
                        ref={ref => this.chooseBoxTitleRef = ref}
                        className='choose-box-title'>
                        {messages('basic-10.key132')/*数据模型*/}
                      </div>
                      }
                      {editData.key !== 'criteria' &&
                      <Select
                        disabled={loading}
                        showSearch
                        value={CurrentSourceReportId}
                        style={{ width: 240 }}
                        placeholder={messages('basic-10.key133')/*请选择数据模型*/}
                        optionFilterProp="children"
                        onChange={this.handleModalChange}
                        // onSearch={this.handleModalOnSearch}
                      >
                        {dataModalList.map(item => {
                          return (<Option value={item.id}>{item.reportName}</Option>);
                        })}
                      </Select>
                      }
                      {editData.key === 'criteria' &&
                      this.renderAllModalList()
                      }
                      <div className={`input-search ${editData.key !== 'criteria' ? 'single-mode' : ''}`}>
                        <Search
                          placeholder={messages('basic-10.key134')/*搜索字段名*/}
                          style={{ width: 240 }}
                          onChange={this.modalSearchOnChange}
                          onSearch={this.handleSearchModalAttributes}
                        />
                      </div>
                    </div>
                  </div>
                  <Spin spinning={loading}>
                    <div className="data-list-box" ref={ref => this.dataListBoxRef = ref}>
                      <DataFakeDropLayout/>
                      {this.renderDataList()}
                      {DataModalAttributes.length === 0 && <div
                        className='place-holder'>{messages('basic-10.key133')/*请选择数据模型*/}</div>}
                    </div>
                  </Spin>
                  <div className="box-groups">
                    {
                      editData.key && boxMap[editData.key || 'default'] && boxMap[editData.key || 'default'].map((singleBoxKey)=>{
                        return <div
                          key={singleBoxKey}
                          className={`dimension-box ${focusBox === singleBoxKey ? 'active' : ''}`}
                          onClick={() => {
                            this.focusBox(singleBoxKey);
                          }}>
                          <DataDropTarget
                            onItemMouseOver={this.handleItemMouseOver}
                            onItemMouseLeave={this.handleItemMouseLeave}
                            onItemClick={this.handleOnItemClick}
                            deleteItem={(widget) => {
                              this.deleteItem(widget, singleBoxKey);
                            }}
                            onDragEnd={this.onDragEnd}
                            type={(editData.key === 'perspective' && singleBoxKey !== 'indicator') ? (singleBoxKey === 'dimension' ? 'dimensionCol' : 'dimensionRow') : singleBoxKey}
                            onSaveI18n={(i18nItem, widget) => {
                              this.onSaveI18n(i18nItem, widget, singleBoxKey);
                            }}
                            onChangeDataStatus={(key, widget, isSequence) => {
                              this.onChangeDataStatus(key, widget, isSequence, editData.key === 'detail_list');
                            }}
                            widgetList={ListMap[singleBoxKey]}
                            onDrop={dropMap[singleBoxKey]}
                            onDragDroppedItem={(widget) => {
                              this.handleOnDragDroppedItem(widget, singleBoxKey);
                            }}
                          />
                        </div>
                      })
                    }
                  </div>
                </div>
                <div className="graphic-box">
                  <div className='tip'>
                    {messages('basic-10.key135')/*图表预览*/}
                    <Popover content={messages('basic-10.key136')/*数据为示例数据，非真实数据*/}>
                      <Icon style={{ marginLeft: 4 }} type="exclamation-circle-o"/>
                    </Popover>
                  </div>
                  <div className="e-chart">
                    {editData.key !== 'criteria' && <Graphic
                      noCard
                      shouldUpdate={noUpdate}
                      fakeDataLength={fakeDataLength}
                      onRef={ref => this.GraphicRef = ref}
                      fakeData={fakeData}
                      noRefresh
                      widget={Object.assign({}, editData)}
                      selectDimensionRowDataList={selectDimensionRowDataList}
                      selectDimensionDataList={selectDimensionDataList}
                      selectIndicatorDataList={selectIndicatorDataList}
                      selectShowDataList={selectShowDataList}
                      selectCriteriaDataList={selectCriteriaDataList}
                    />}
                    {editData.key === 'criteria' &&
                    <IndexAdvanceSearch
                      widget={Object.assign({}, editData)}
                      customReportData={customReportData}
                      selectCriteriaDataList={selectCriteriaDataList}
                    />
                    }
                  </div>
                </div>
              </Content>
              <Sider style={{ backgroundColor: '#fff' }} width={320}>
                <Tabs defaultActiveKey="1" onChange={this.onTabChange}>
                  <TabPane tab={messages('common.baseInfo')/*基本信息*/} key="1">
                    <Form className='form-box'>
                      {editData.key !== 'criteria' && <Form.Item colon={false} required
                                                                 label={messages('basic-10.key137')/*图表名称*/}>
                        {getFieldDecorator('name', {
                          rules: [InputLanguage.required],
                          initialValue: {
                            name: editData.name,
                            i18n: editData.i18n ? editData.i18n.name : []
                          }
                        })(
                          <InputLanguage/>
                        )}
                      </Form.Item>}
                      {editData.key === 'criteria' &&
                      <Form.Item label={messages('basic-10.key138')/*作用范围*/}>
                        <Input value={messages('basic-10.key139')/*全部元素*/} disabled/>
                      </Form.Item>
                      }
                    </Form>
                    {(editData.key !== 'detail_list' && editData.key !== 'criteria') &&
                    <div className={`graphic-info-box ${['zh_cn, zh_tw'].indexOf(code) !== -1 ? '' : 'en'}`}>
                      <div className="info-title">{messages('basic-10.key140')/*图表类型*/}</div>
                      <div className='flex-wrapper'>
                        {this.renderGraphic()}
                      </div>
                    </div>
                    }
                    {(editData.key === 'indicatrix' && selectDimensionDataList.length === 0) &&
                    <div className="graphic-info-box">
                      <div className="info-title">{messages('basic-10.key141')/*字体大小*/}</div>
                      <div className='flex-wrapper'>
                        {this.renderFontSizeOptions()}
                      </div>
                    </div>
                    }
                    {['detail_list', 'perspective'].indexOf(editData.key) !== -1 &&
                    <div className='graphic-info-box'>
                      <div className="info-title">{messages('basic-10.key142')/*操作权限*/}</div>
                      {this.renderOperateSetting()}
                    </div>
                    }
                    {(editData.key !== 'indicatrix' || selectDimensionDataList.length !== 0) && !(['criteria', 'perspective'].indexOf(editData.key) !== -1) &&
                    <div className='graphic-info-box '>
                      <div className="info-title">{messages('basic-10.key143')/*展示设置*/}</div>
                      {this.renderDisplaySetting()}
                    </div>
                    }
                    {editData.key === 'criteria' && selectCriteriaDataList.length !== 0 &&
                    <div className='graphic-info-box'>
                      <div className="info-title">{messages('basic-10.key144')/*默认值设置*/}</div>
                      {this.renderDefaultValueList()}
                    </div>
                    }
                    {!(['criteria', 'detail_list', 'indicatrix', 'radar', 'perspective'].indexOf(editData.key) !== -1) && linkableList && linkableList.length !== 0 &&
                    <div className='graphic-info-box'>
                      <div className="info-title">{messages('basic-10.key145')/*图形表联动*/}</div>
                      {this.renderLinkableCharts()}
                    </div>
                    }
                  </TabPane>
                </Tabs>
              </Sider>
            </Layout>
          </div>
        </Spin>
      </div>
    );
  }
}

EditCustomReport.propTypes = {};

export default EditCustomReport;
